package com.linq.cool.beauty.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.linq.cool.beauty.domain.BeautyProduct;
import com.linq.cool.beauty.domain.BeautyProductCollection;
import com.linq.cool.beauty.domain.BeautyProductStatistical;
import com.linq.cool.beauty.repository.BeautyProductCollectionRepository;
import com.linq.cool.beauty.service.BeautyProductCollectionService;
import com.linq.cool.beauty.service.BeautyProductService;
import com.linq.cool.beauty.service.BeautyProductStatisticalService;
import com.linq.cool.beauty.vo.BeautyProductCollectionVO;
import com.linq.cool.common.core.utils.BeanUtils;
import com.linq.cool.common.core.utils.IdWorker;
import com.linq.cool.common.core.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: yqlin
 * @Date: 2021/2/9 14:11
 * @Description:
 * @Version: 1.0.0
 */
@Slf4j
@Service
public class BeautyProductCollectionImpl implements BeautyProductCollectionService {
    @Autowired
    private BeautyProductCollectionRepository productCollectionRespository;
    @Autowired
    private BeautyProductService productService;
    @Autowired
    private BeautyProductStatisticalService productStatisticalService;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void changeCollection(BeautyProductCollection productCollection) {
        //  先查询  如果存在就取消收藏 也就是 删除 不存在就新增
        BeautyProductCollection one = productCollectionRespository.findByProductIdAndMemberId(productCollection.getProductId(), SecurityUtils.getUserId());
        BeautyProductStatistical productStatistical = productStatisticalService.getOne(new LambdaQueryWrapper<BeautyProductStatistical>()
                                                                                               .eq(BeautyProductStatistical::getProductId, productCollection.getProductId())
        );
        try {
            if (null == one) {
                // 根据商品id查询商品
                BeautyProduct product = productService.getById(productCollection.getProductId());
                productCollection
                        .setProductId(productCollection.getProductId())
                        .setId(idWorker.nextId())
                        .setProductPic(product.getPic())
                        .setCreateTime(new Date().toString())
                        .setProductName(product.getName())
                        .setProductBrandId(product.getBrandId())
                        .setProductBrandName(product.getBrandName())
                        .setProductCategoryId(product.getProductCategoryId())
                        .setProductPrice(product.getPrice())
                        .setMemberId(SecurityUtils.getUserId());
                // 存入mongo
                productCollectionRespository.save(productCollection);
                // 更新商品统计信息
                productStatistical.setCollectionCount(productStatistical.getCollectionCount() + 1);
            } else {
                //删除
                productCollectionRespository.deleteById(one.getId());
                // 减少收藏
                productStatistical.setCollectionCount(productStatistical.getCollectionCount() - 1);
            }
            productStatisticalService.updateById(productStatistical);
        } catch (Exception e) {
            log.error("切换收藏状态错误:{}", e.getMessage());
        }

    }

    @Override
    public BeautyProductCollection getByProductId(Long productId) {
        return productCollectionRespository.findByProductIdAndMemberId(productId, SecurityUtils.getUserId());
    }

    @Override
    public List<BeautyProductCollectionVO> listByPage(Long current, long size) {
        Query query = new Query();
        // 设置参数
        query.addCriteria(Criteria.where("member_id").is(SecurityUtils.getUserId()));
        // 设置跳过多少条
        query.skip((current - 1) * size);
        // 取出多少条
        query.limit(Math.toIntExact(size));
        // 构造排序对象
        Sort.Order order = new Sort.Order(Sort.Direction.DESC, "create_time");
        // 设置排序对象
        query.with(Sort.by(order));
        List<BeautyProductCollection> productCollections = mongoTemplate.find(query, BeautyProductCollection.class);
        List<Long> productIds = productCollections.stream().map(BeautyProductCollection::getProductId).collect(Collectors.toList());
        List<BeautyProductCollectionVO> voList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(productIds)) {
            List<BeautyProductStatistical> productStatisticals = productStatisticalService.list(new LambdaQueryWrapper<BeautyProductStatistical>()
                                                                                                        .in(BeautyProductStatistical::getProductId, productIds)
            );
            voList = productCollections.stream().map(item -> {
                BeautyProductCollectionVO vo = new BeautyProductCollectionVO();
                BeanUtils.copyProperties(item, vo);
                // 匹配到该商品对应的收藏信息
                BeautyProductStatistical statistic = productStatisticals.stream().filter(s -> s.getProductId().equals(item.getProductId())).findFirst().orElse(new BeautyProductStatistical());
                vo.setCollectionCount(statistic.getCollectionCount());
                return vo;
            }).collect(Collectors.toList());
        }
        return voList;
    }
}
